package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.ExprMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import com.itheima.service.ExprService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    /**
     * 分页查询
     *
     * @param param     查询条件
     * @return 分页结果
     */

    @Resource
    private DeptService deptService;
    @Resource
    private ExprService exprService;
    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("entry_date"));
        //需要判断条件
        LambdaQueryWrapper<Emp> wrapper = Wrappers.<Emp>lambdaQuery()
                .like(param.getName() != null && !"".equals(param.getName()), Emp::getName, param.getName())
                //性别
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                //入职开始与结束时间begin，end
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());
        Page<Emp> page1 = page(page,wrapper);
        //要加入部门名称deptName
        //现在有部门id
        List<Emp> empList = page1.getRecords();
        //获取部门id
        Set<Integer> deptIds = empList.stream().map(emp -> emp.getDeptId()).collect(Collectors.toSet());
        //根据部门id查部门列表
        List<Dept> deptList = deptService.listByIds(deptIds);
        //把部门里的id和部门名称当做键值对存Map里
        Map<Integer, String> deptMap = deptList.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
        //循环遍历emplist，根据已有的部门id把相对应的部门名称存进去
        for (Emp emp : empList) {
            Integer deptId = emp.getDeptId();
            emp.setDeptName(deptMap.get(deptId));
        }
        return new PageResult<>(page1.getTotal(),empList);
    }

    //新增员工（员工信息+工作经历）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        //新增员工信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);
        //新增员工工作经历
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        exprService.saveBatch(exprList);
    }


    @Override
    public Emp getEmpById(Integer id) {

        //根据id查员工信息
        Emp emp = getById(id);

        //根据id查员工经历
        List<EmpExpr> exprList = exprService.list(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, id));
        emp.setExprList(exprList);
        return emp;
    }

@Override
@Transactional(rollbackFor = Exception.class)
public void updateEmp(Emp emp) {

    // 修改员工信息
    emp.setUpdateTime(LocalDateTime.now());
    updateById(emp);

    // 修改员工工作经历
    List<EmpExpr> exprList = emp.getExprList();

    // 先删除该员工的所有工作经历
    exprService.remove(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));

    // 再批量保存新的工作经历
    if (exprList != null && !exprList.isEmpty()) {
        // 设置员工ID到每个工作经历对象
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
    }
    exprService.saveBatch(exprList);
}

  @Override
@Transactional(rollbackFor = Exception.class)
public void removeEmpsByIds(List<Integer> ids) {
    // 参数校验
    if (ids == null || ids.isEmpty()) {
        return;
    }

    //批量删除员工信息
    removeByIds(ids);
    //批量删除员工工作经历
    exprService.remove(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId, ids));
}



}
